package com.jackrain.clouddata.sys.Listenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.clouddata.oms.util.KeyValueUtils;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component("com.jackrain.clouddata.sys.Listenter.FA_StorageMessageProcess")
@Slf4j
public class FA_StorageMessageProcess implements MessageProcess {
    public FA_StorageMessageProcess(){ }

    @Override
    public void process(Object paramObject, String tag) throws Exception{
        JSONObject paramJson = (JSONObject)paramObject;
        insertSup(paramJson,tag);
    }

    //@Transactional
    private void insertSup(JSONObject paramJson,String tag){
        log.info("****FA_StorageMessageProcess*****");

        //根据tag获取公司ID
        String clientIdSql = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE ISACTIVE='Y' AND TAGNAME = ?";
        JSONObject clientJson = QueryEngine.getInstance().doQueryObject(clientIdSql,new Object[]{tag});
        if (clientJson == null){
            throw new NDSException("公司ID未找到!");
        }
        Long clientId = clientJson.getLong("AD_CLIENT_ID");

        //获取表名NAME
        String tableName = paramJson.getString("name");
        //获取结果Array
        JSONArray paramArray = paramJson.getJSONArray("value");

        int m=0,n=0;
        boolean insert=false,update=false;

        String selectSql = "SELECT COUNT(1) FROM FA_STORAGEITEM WHERE AD_CLIENT_ID=? AND SKUNO=? AND STORECODE=?";
//        String updateSql = null;
//        String insertSql = null;

        JSONArray insertArray = new JSONArray();
        JSONArray updateArray = new JSONArray();
        int incount = 0;

        for (int i=0;i<paramArray.size();i++){
            JSONObject jsonObject = paramArray.getJSONObject(i);
            JSONObject omsJson = JSON.parseObject(JSON.toJSONString(jsonObject,new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);
            for (int l = 0; l < omsJson.keySet().size(); l++) {
                String key = (String) omsJson.keySet().toArray()[l];
                String values=omsJson.getString(key);
                if(values==null)
                {
                    omsJson.put(key,"");
                }
                if (key.contains("DATE")) {
                    omsJson.put(key, TypeUtils.castToDate(omsJson.get(key)));
                }
            }
            omsJson.remove("AD_CLIENT_ID");
            omsJson.put("AD_CLIENT_ID",clientId);
           String skunonum= omsJson.getString("SKUNO");
           String STORECODEomg=omsJson.getString("STORECODE");
           if(skunonum==null || STORECODEomg==null)
           {
               throw new NDSException("PROVALUE="+(omsJson.getString("PROVALUE"))+"SKUNO或STORECODE是空值");
           }
            //去重
            int count=QueryEngine.getInstance().doQueryInt(selectSql, new Object[]{clientId,skunonum,STORECODEomg});

            if(count > 0){//更新
                //调换SUPCODE位置
                String STORECODE=omsJson.getString("STORECODE");
                omsJson.remove("STORECODE");
                omsJson.remove("AD_CLIENT_ID");
                String PROVALUE = (String )omsJson.getString("SKUNO");
                omsJson.remove("SKUNO");
//                omsJson.put("STORECODE",STORECode);
//
//                omsJson.remove("STORECODE");
                String updatestorageSql = "UPDATE FA_STORAGEITEM SET " + KeyValueUtils.keyUpdateAppend(omsJson.keySet()) + " WHERE STORECODE=? AND AD_CLIENT_ID=? AND SKUNO=?";
                omsJson.put("STORECODE",STORECODE);
                omsJson.put("AD_CLIENT_ID", clientId);
                omsJson.put("SKUNO",PROVALUE);
                for (int j = 0; j <omsJson.keySet().size(); j++) {
                    String key = (String) omsJson.keySet().toArray()[j];
                    String value =omsJson.getString(key);
                    if (value == null) {
                        if (!key.contains("DATE")) {
                            omsJson.put(key, "");
                        } else {
                            omsJson.remove(key);
                            updatestorageSql = updatestorageSql.replace(key + "=?,", "");
                        }
                    }
                }
                QueryEngine.getInstance().executeUpdate(updatestorageSql,omsJson.values().toArray());
            }
            else{//插入
//                omsJson.put("ID", Tools.getSequence("FA_STORAGEITEM"));  //ID
                omsJson.put("AD_CLIENT_ID", clientId);
                omsJson.put("ID", Tools.getSequence("FA_STORAGEITEM"));
                insertArray.set(incount,  omsJson);
                incount = incount + 1;
                //生成insertaSql语句
//                if(!insert){
//                    StringBuffer sb = new StringBuffer("INSERT INTO FA_STORAGEITEM (");
//                    StringBuffer q = new StringBuffer();
//                    for (String s:omsJson.keySet()) {
//                        if(s.equals("ID")){
//                            q.append( "?" );
//                            sb.append( s +") VALUES(" + q.toString() + ")" );
//                        }else{
//                            sb.append( s + "," );
//                            q.append( "?," );
//                        }
//                    }
//                    insertSql = sb.toString();
//                    insert = true;
//                }
//
//                insertArray.set(n++,omsJson);
            }

        }
//        if(update){
//            QueryEngine.getInstance().executeBatchUpdate(updateSql,updateArray);//批量更新
//        }
        if (insertArray != null && insertArray.size() > 0) {
            StringBuffer insertSql = new StringBuffer();
            insertSql.append("INSERT INTO FA_STORAGEITEM (" + KeyValueUtils.keyAppend(insertArray.getJSONObject(0).keySet()) + ") VALUES(").append(KeyValueUtils.valueAppend(insertArray.getJSONObject(0).size())).append(")");
            QueryEngine.getInstance().executeBatchUpdate(insertSql.toString(), insertArray);
//            QueryEngine.getInstance().executeBatchUpdate(insertSql,insertArray);//批量插入
        }

    }

}
